﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Navigation;
using CuteRibs.D3Armory.Models;
using CuteRibs.D3Armory.Resources;
using CuteRibs.D3Armory.ViewModels;
using CuteRibs.MVVMLib;

namespace CuteRibs.D3Armory.Views
{
	public partial class ProfilePage : CuteRibs.D3Armory.Views.PageBase
	{
		private ProfilePageViewModel myViewModel;

		public ProfilePageViewModel MyViewModel
		{
			get
			{
				if (this.myViewModel == null)
				{
					this.myViewModel = (ProfilePageViewModel)this.DataContext;
				}

				return this.myViewModel;
			}
		}

		public Realm Realm { get; set; }
		public string BattleTag { get; set; }

		public ProfilePage()
			: base()
		{
			InitializeComponent();

			this.Loaded += delegate
			{
				this.AppButtons[0].Text = AppRes.btnRefresh;
				this.AppButtons[1].Text = AppRes.btnDelete;
			};
		}

		private async void LoadData(bool refresh = false)
		{
			this.MyViewModel.ShowProgressBar = true;
			Profile profile = null;

			try
			{
				if (refresh)
				{
					profile = await App.GetProfile(this.Realm, this.BattleTag);
				}
				else
				{
					profile = await App.LoadProfile(this.Realm, this.BattleTag);
				}

				if (!string.IsNullOrEmpty(profile.ErrorCode))
				{
					App.ShowAlert(string.Format("{0}: {1}", profile.ErrorCode, profile.ErrorReason));
					this.MyViewModel.ProfileViewModel = null;
				}
				else
				{
					this.MyViewModel.ProfileViewModel = new ProfileViewModel(profile);
				}
			}
			catch (Exception ex)
			{
				if (ex is WebException)
				{
					App.ShowAlert(AppRes.MsgDataAccessError);
				}
				else
				{
					App.ShowError(new AppException(ex, this.Realm, this.BattleTag));
				}
			}

			this.MyViewModel.ShowProgressBar = false;
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			string region, battleTag;
			this.NavigationContext.QueryString.TryGetValue("Region", out region);
			this.NavigationContext.QueryString.TryGetValue("BattleTag", out battleTag);
			this.Realm = Realm.Parse(region);
			this.BattleTag = battleTag;
			this.LoadData();
		}

		private void Hero_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			var frameworkElement = sender as FrameworkElement;
			var viewModel = frameworkElement.DataContext as LargeHeroViewModel;
			this.NavigationService.Navigate("/Views/HeroPage.xaml?Region={0}&BattleTag={1}&Hero={2}", this.Realm.Region.ToString(), this.BattleTag, viewModel.Id);
		}

		private void btnRefresh_Click(object sender, EventArgs e)
		{
			this.LoadData(true);
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			if (App.ShowConfirm(AppRes.MsgProfileDeleteConfirm) == MessageBoxResult.OK)
			{
				App.DeleteProfile(this.Realm, this.BattleTag);
				this.NavigationService.GoBack();
			}
		}
	}
}
